package com.zhike.service.file;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.liuxp.minioplus.api.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhike.common.conf.IMBaseConf;
import com.zhike.common.constant.Constants;
import com.zhike.common.constant.SysConfigConstants;
import com.zhike.common.enums.YesNoEnum;
import com.zhike.common.utils.AliSecurityCheckUtils;
import com.zhike.mapper.group.GroupBaseMapper;
import com.zhike.service.system.ISystemConfigService;
import com.zhike.utils.cache.GroupsInfoCacheProvider;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class GroupAvatarUploader extends UploaderRoot {
    @Resource
    private IMBaseConf baseConf;

    @Autowired
    private ISystemConfigService systemConfigService;

    @Autowired
    private StorageService storageService;

    @Resource
    private GroupBaseMapper groupBaseMapper;

    @Autowired
    private GroupsInfoCacheProvider groupsInfoCacheProvider;

    @Override
    public String getFileSaveDir() {
        return baseConf.getDIR_USER_AVATARGROUP_DIR();
    }

    @Override
    public String getPathTag() {
        return Constants.UPLOAD_GROUP_AVATAR;
    }

    @Override
    public void onUploadSucess(HashMap<String, Object> parametersFromClient) throws Exception {
        String url = (String) parametersFromClient.get("url");
        // String userUid = (String) parametersFromClient.get("user_uid");
        String groupId = (String) parametersFromClient.get("group_id");
        // 因为服务端是支持多文件上传的API，所以客户端单独把文件名带过来了，方便使用！
        String fileName = (String) parametersFromClient.get("file_name");

        log.debug("[" + getDebugTAG() + "] 群" + groupId + "的头像文件" + fileName + "数据上传成功，马上处理其它业务逻辑...");

        // 客户端传过来的数据（参数）的合法性检查
        if (StringUtils.isNotBlank(fileName) && StringUtils.isNotBlank(url)) {
            Integer conf = systemConfigService.getValueByKeyAsInt(SysConfigConstants.CONFIG_TYPE_SECURITY,
                    SysConfigConstants.CONFIG_USER_PROFILE);
            if (conf != null && conf.equals(YesNoEnum.YES.getValue())) {
                // 校验头像图片是否合规
                if (!AliSecurityCheckUtils.imageScan(url, "profilePhotoCheck")) {
                    log.warn("FileKey: {} 不合规", fileName);
                    // 删除
                    storageService.remove(fileName);
                    log.info("uid: {} 头像图片: {}不合规 已删除", groupId, fileName);
                    return;
                }
            }

            // 用户新头像数据成功保存成文件之后要做的事：删除老头像文
            // 件并把最新的文件名更新到用户数据表中
            long t = System.currentTimeMillis();
            groupBaseMapper.updateGroupAvatar(fileName, groupId, t);
            groupsInfoCacheProvider.reloadOneCache(groupId);
            parametersFromClient.put("avatar_updatetime", t);
        } else {
            throw new Exception("[" + getDebugTAG() + "] 无效的参数：userUid=" + groupId + ", fileName=" + fileName + ".");
        }
    }

    @Override
    public void onUploadFailure(Exception ex) {
        log.error("[" + getDebugTAG() + "] 处理群头像上传时出错了，" + ex.getMessage(), ex);
    }

    @Override
    public String getDebugTAG() {
        return "HTTP头像上传";
    }

    @Override
    public Set<String> getDetectedTypes() {
        Set<String> allowExtensions = new HashSet<>();
        allowExtensions.add("image/png");
        allowExtensions.add("image/jpeg");
        allowExtensions.add("image/jpg");
        allowExtensions.add("image/gif");
        return allowExtensions;
    }

}
